package com.furongji.common.utils;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedissonLockUtil {

    private final RedissonClient redissonClient;

    public RedissonLockUtil(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    /**
     * 获取锁，默认等待时间为0（立即尝试获取锁），默认锁自动释放时间30秒
     *
     * @param lockKey 锁的名称
     * @return 获取锁成功返回true，否则false
     */
    public boolean tryLock(String lockKey) {
        return tryLock(lockKey, 0, 30, TimeUnit.SECONDS);
    }

    /**
     * 尝试获取锁
     *
     * @param lockKey   锁的名称
     * @param waitTime  等待获取锁的时间，超过后返回失败
     * @param leaseTime 锁自动释放时间，避免死锁
     * @param timeUnit  时间单位
     * @return 获取锁成功返回true，否则false
     */
    public boolean tryLock(String lockKey, long waitTime, long leaseTime, TimeUnit timeUnit) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            return lock.tryLock(waitTime, leaseTime, timeUnit);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return false;
        }
    }

    /**
     * 释放锁
     *
     * @param lockKey 锁的名称
     */
    public void unlock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        if (lock.isHeldByCurrentThread()) { // 只释放自己持有的锁，避免误释放
            lock.unlock();
        }
    }
}

